using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using NerdDinner.Web.Models.Repository;
using NerdDinner.Web.Helpers;

namespace NerdDinner.Web.Controllers
{
    [HandleElmahError]
    public class JsonDinner
    {
        public int DinnerId { get; set; }
        public string Title { get; set; }
        public double Latitude { get; set; }
        public double Longitude { get; set; }
        public string Description { get; set; }
        public int RSVPCount { get; set; }
    }

    public class SearchController : Controller
    {
        private IDinnerRepository _repository;

        public SearchController()
        {
            _repository = new DinnerRepository();
        }

        //
        // AJAX: /Search/SearchByLocation?longitude=45&latitude=-90

        [AcceptVerbs( HttpVerbs.Post )]
        public ActionResult SearchByLocation( float latitude, float longitude, int distance )
        {
            var dinners = _repository.FindByLocation( latitude, longitude, distance );

            var jsonDinners = from dinner in dinners
                              select new JsonDinner
                              {
                                  DinnerId = dinner.DinnerId,
                                  Latitude = dinner.Latitude,
                                  Longitude = dinner.Longitude,
                                  Title = dinner.Title,
                                  Description = dinner.Description,
                                  RSVPCount = dinner.RSVPs.Count
                              };

            return Json( jsonDinners.ToList() );
        }

        //
        // AJAX: /Search/UpComingDinners

        [AcceptVerbs( HttpVerbs.Post )]
        public ActionResult UpComingDinners()
        {
            var dinners = _repository.FindUpcomingDinners();

            var jsonDinners = from dinner in dinners
                              select new JsonDinner
                              {
                                  DinnerId = dinner.DinnerId,
                                  Latitude = dinner.Latitude,
                                  Longitude = dinner.Longitude,
                                  Title = dinner.Title,
                                  Description = dinner.Description,
                                  RSVPCount = dinner.RSVPs.Count
                              };

            return Json( jsonDinners.ToList() );
        }
    }
}
